package com.fastadmin.mapper.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.fastadmin.pojo.FUser;
import com.fastadmin.pojo.FastParam;
import com.xphsc.easyjdbc.EasyJdbcTemplate;
import com.xphsc.easyjdbc.core.exception.JdbcDataException;
import com.xphsc.easyjdbc.page.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.xphsc.easyjdbc.core.metadata.ElementResolver;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Repository
@Slf4j
public class FUserMapper extends BaseMapper {
    @Autowired
    EasyJdbcTemplate easyJdbcTemplate;
    String tableName = ElementResolver.resolve(FUser.class).getTable();

    public PageInfo<FUser> findByFastParam(FastParam fastParam) {
        String tableName = ElementResolver.resolve(FUser.class).getTable();
        PageInfo<FUser> pageInfo = this.easyJdbcTemplate.findByPage(fastParam.getSql(tableName), FUser.class, fastParam.getOffset(), fastParam.getLimit());
        return pageInfo;
    }

    public FUser findById(Long ids) {
        FUser fuser = this.easyJdbcTemplate.getByPrimaryKey(FUser.class, ids);
        return fuser;
    }

    public void deleteById(String id) {
        this.easyJdbcTemplate.deleteByPrimaryKey(FUser.class, id);
    }

    public void update(FUser fuser) {
        fuser.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        this.easyJdbcTemplate.update(fuser);
    }

    public Object save(FUser fuser) {
        fuser.setCreate_time(new Timestamp(System.currentTimeMillis()));
        fuser.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        return this.easyJdbcTemplate.insertKey(fuser);

    }

    public List<FUser> findByIds(String ids) {
        if (StrUtil.isBlank(ids)) {
            return CollUtil.newArrayList();
        }
        return this.easyJdbcTemplate.findByIds(FUser.class, Arrays.asList(StrUtil.splitToArray(ids, ',')));

    }

    public FUser findByOpenId(String openid) {
        StrBuilder sql = StrBuilder.create("SELECT * FROM "+tableName+" WHERE open_id =? AND status=0 ");
        List<FUser> fUsers = easyJdbcTemplate.find(sql.toString(), FUser.class, openid);
        if (fUsers.size() > 0) {
            return fUsers.get(0);
        } else {
            return null;
        }
    }
}
